import HelperFunctions as HF
import numpy as np
from numpy import array
from scipy import linalg
from datetime import datetime
from time import strftime
import random
import csv

'''
add a field to identify the cancer in population point shapefile

***revision of test12.py***
randomly choose the point from shapefile to add cancer
'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_point_value_lists():
    data = []
    fn = points_CSV

    ra = csv.DictReader(file(fn), dialect="excel")
    for record in ra:
        temp = int(float(record["region_id"]))
        data.append(temp)
        
    return data

def build_tp_value_lists():
    data = []
    fn = TP_csv

    ra = csv.DictReader(file(fn), dialect="excel")
    for record in ra:
        temp = int(float(record["rate_id"]))
        data.append(temp)
        
    return data

def cal_cancer_case(iLen):
    #add cancer
    #print "========================Add Cancer============================="
    #incidence = [0.010,0.015,0.005,0.015,0.015,0.005,0.005,0.015]

    #[high rate, low rate, relative high rate, relative low rate]    
    incidence = [0.011, 0.009, 0.015, 0.005]
    
    sigma = 0.0010

    #polygon id within high risk area 
    HighAreaID = [3,4,5,6]
    
    #polygon id within low risk area 
    LowAreaID = [7,8,9]
    TotalPop = len(points_data)
    #print TotalPop
    #cancer = 0 #total of cancer case
    i = 0
    regCancer = np.fromfunction(generate_zero_list, (iLen,))
    
    while i < TotalPop:
        # if the point is within the relative high risk area
        #print int(points_data[i])
        #int(TP_data[int(points_data[i])])
        if TP_data[points_data[i]] in HighAreaID:
            iIncidence = 2
        #if the point is within the relative low risk area
        elif TP_data[points_data[i]] in LowAreaID:
            iIncidence = 3
        elif TP_data[points_data[i]] == 1:
            iIncidence = 0
        elif TP_data[points_data[i]] == 2:
            iIncidence = 1
        else:
            print "error in risk id in TP_data or region id in points_data"
            return NULL
        #iIncidence = areaData[i][1]
        tempIncidence = np.random.normal(incidence[iIncidence], sigma, 1)
        if np.random.random() < tempIncidence[0]:
            #areaData[i][2] = 1
            regCancer[points_data[i]] = regCancer[points_data[i]] + 1  #total of cancer case
        i = i + 1
    return regCancer

def generate_zero_list(i):
    return i-i

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "======================================================="
    print "begin at " + getCurTime()
    #inputs = get_inputs()
    
    points_CSV = "C:/_DATA/CancerData/test/Feb10/1m_point_TP1000.csv"  # points with its Thessien Polygon ID
    TP_csv = "C:/_DATA/CancerData/test/Feb10/TP1000.csv" #thessien polygon id with its high or low region id
    #high or low regioni id
    # 1: high   2: low  3-6: relative high  7-9: relative low
    
    points_data = build_point_value_lists()
    
    TP_data = build_tp_value_lists()
    
    #print TP_data[370]
    
    dis_reg = set(points_data)
    #del regionData
    #regCancer = np.fromfunction(generate_zero_list, (len(dis_reg)))
    regCancerT = np.arange(0, len(dis_reg), 1)
    
    i = 0
    iterNum = 20
    while i < iterNum:
        print i
        i = i + 1
        random.shuffle(points_data)
        temp = cal_cancer_case(len(dis_reg))                               
        regCancerT = np.append(regCancerT, temp)
    regCancerT.shape = (iterNum + 1, -1)
    #temp = regCancerT.transpose
    temp = np.transpose(regCancerT)
    #print temp
    np.savetxt("C:/_DATA/CancerData/test/Feb10/temp.txt", temp, delimiter=',')
    
    print "end at " + getCurTime()
